package cn.richard.demo.ruleengine.config;

import java.util.Properties;
import java.util.concurrent.Executor;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class AbsNacosPropertiesConfigListener {
    /**
     * 服务器地址
     */
    @Value("${spring.cloud.nacos.config.server-addr}")
    private String serverAddr;
    
    @Autowired 
    private Environment env;
    
    private String namespace;
    private String group;
    private String dataId;

    @PostConstruct
    private void init() {
        //服务地址
        log.info("服务地址：{}", serverAddr);

        //初始化目标配置地址
        initGav(env);
        
        //读取配置并注册修改监听器
        readConfigAndListen();
    }

    private void initGav(Environment env) {
    	namespace = getNamespace(env);
    	group = getGroup(env);
    	dataId = getDataId(env);
	}

	protected abstract String getDataId(Environment env);

	protected abstract String getGroup(Environment env);

	protected abstract String getNamespace(Environment env);

	private void readConfigAndListen() {
        try {
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            properties.put(PropertyKeyConst.NAMESPACE, namespace);
            ConfigService configService = NacosFactory.createConfigService(properties);

            String content = configService.getConfig(dataId, group, 5000);
            if (StringUtils.isEmpty(content)) {
                log.warn("目标配置内容为空,跳过监听");
                return;
            }

            log.info("初始配置内容读取: {}", content);
            log.info("开始注册修改监听: {}", dataId);
            configService.addListener(dataId, group, new Listener() {

                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("{} 本次修改后的内容: {}", dataId, configInfo);
                    onConfigInfoChanged();
                }

                @Override
                public Executor getExecutor() {
                    return null;
                }
            });
            log.info("结束注册修改监听: {}", dataId);

        } catch (Exception e) {
            log.error("Nacos配置相关异常:{}", e.getMessage());
        }
    }
    
    protected abstract void onConfigInfoChanged();
}
